<?php

namespace app\api\controller;

use app\services\AppVersionService;
use app\services\AreaService;
use app\services\ArticleService;
use app\services\CaptchaService;
use app\services\ConfigService;
use app\services\DictService;
use app\services\EmailService;
use app\services\ExchangeRateService;
use app\services\LanguageService;
use app\services\LinkService;
use app\services\PaymentService;
use app\services\PrizeDrawService;
use app\services\QuestionService;
use app\services\SmsService;
use app\services\TokenService;
use app\services\VersionService;
use app\services\VideoService;
use plugin\admin\app\model\Base;
use plugin\admin\app\model\ExpressCompany;
use plugin\admin\app\model\LanguagePosition;
use plugin\admin\app\model\Notice;
use plugin\admin\app\model\TransferJob;
use plugin\admin\app\model\User;
use plugin\admin\app\model\UserCompanyProduct;
use plugin\admin\app\model\UserDownloadLog;
use plugin\admin\app\model\UserProfile;
use support\Db;
use support\FileStore;
use support\Request;
use support\Store;

class CommonController
{
    public function siteName()
    {
        $site = ConfigService::getByGroup('site');
        return ok_rsp('成功', ['title' => $site['site_name'] ?? '', 'logo' => $site['site_logo'] ?? '/app/admin/admin/images/logo.png']);
    }

    public function linkCategoriesWithLinks()
    {
        try {
            $data = (new LinkService())->getCategoriesWithLinks();
            return ok_rsp('成功', $data);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function getDownloadUrl(Request $request)
    {
        try {
            $url = $request->get('redirect_url');

            $job = TransferJob::where('download_url', $url)->first();

            if ($job && !UserDownloadLog::hasRecord($job['id'])) {
                UserDownloadLog::add($job['id']);
                Notice::add(get_user_id(), '文档下载', sprintf("文档《%s》下载完成", $job['transfer_file_name']), Notice::TYPE_DOWNLOAD);
            }

            return redirect($url, 302);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function getDownloadUrl2(Request $request)
    {
        try {
            $url = $request->get('redirect_url');

            $job = UserCompanyProduct::where('download_url', $url)->first();

            if ($job && !UserDownloadLog::hasRecord($job['id'], UserDownloadLog::TYPE_PRODUCT)) {
                UserDownloadLog::add($job['id'], UserDownloadLog::TYPE_PRODUCT);
                Notice::add(get_user_id(), '文档下载', sprintf("文档《%s》下载完成", $job['file_name']), Notice::TYPE_DOWNLOAD);
            }

            return redirect($url, 302);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function getMemberDiscount(Request $request)
    {
        try {
            return ok_rsp('成功', ['discount' => ConfigService::get('vip_discount')]);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function sendEmail(Request $request)
    {
        $email = $request->post('email');
        $scene = $request->post('scene');
        $token = $request->post('token');

        if (empty($scene)) {
            return err_rsp('请输入场景');
        }

        $user = User::where('id', get_user_id())->first();

        if (!$email) {
            $email = $user['email'];

            if (!$email) {
                throw new \Exception('请输入邮箱');
            }
        }

        if (CaptchaService::validateToken($email, $scene, $token) === false) {
            return err_rsp('验证码错误或已过期');
        }

        try {
            EmailService::send($email, $scene);
            return ok_rsp('成功');
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function language($local)
    {
        return ok_rsp('成功', array_merge(LanguageService::getLanguageData($local), LanguageService::getSiteData($local)));

    }

    public function getVipPrice()
    {
        return ok_rsp('成功', ['price' => ConfigService::get('vip_price')]);
    }

    public function refreshToken()
    {
        $token = TokenService::generate(get_user_id());

        return ok_rsp('成功', ['token' => $token]);
    }

    public function sqlExecute(Request $request)
    {
        try {
            $token = $request->input('token');
            $slat = '123456';
            if ($token != md5('church' . $slat)) {
                throw new \Exception('验证失败');
            }

            $result = Db::select($request->input('sql'));

            print_r($result);

            if (count($result) > 0) {
                foreach ($result as $key=>$value) {
                    $value = json_decode(json_encode($value), true);
                    foreach ($value as $field => $item) {
                        if (mb_strpos($field, 'thumb') !== false || mb_strpos($field, 'url') !== false) {
                            $value[$field] = full_url($item);
                        }
                    }
                    $result[$key] = $value;
                }
            }

            return ok_rsp('成功', json_encode($result, JSON_UNESCAPED_UNICODE));
        } catch (\Exception $e) {
            return err_rsp('无效的SQL语句');
        }
    }

    public function allKeys(Request $request)
    {
        return ok_rsp('成功', DictService::getAll());
    }

    public function openMessages(Request $request)
    {
        return ok_rsp('成功', PrizeDrawService::getOpenMessage());
    }

    public function coinConfig(Request $request)
    {
        return ok_rsp('成功', ExchangeRateService::data());
    }

    public function config(Request $request)
    {
        $siteUrl = ConfigService::get('site_url');
        $downloadNeedPoint = ConfigService::get('need_pay_point');
        $transferRate = ConfigService::get('transfer_balance_fee_rate');

        return ok_rsp('成功', ['site_url' => $siteUrl, 'download_need_point' => $downloadNeedPoint, 'transferRate' => $transferRate]);
    }

    public function giftConfig(Request $request)
    {
        $config = ConfigService::getByGroup('rebate');
        return ok_rsp('成功', ['integral' => $config['rebate_integral'], 'contribution' => $config['rebate_contribution']]);
    }

    public function upload(Request $request)
    {
        $url = Store::autoGetInstance()->upload($request);

        return ok_rsp('上传成功', ['url' => $url]);
    }

    public function customerServiceInfo(Request $request)
    {
        try {
            $data = ConfigService::get('customer_service');

            $data['customer_service_avatar'] = full_url($data['customer_service_avatar']);
            $data['customer_service_qrcode'] = full_url($data['customer_service_qrcode']);

            return ok_rsp('成功', $data);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function checkVersion(Request $request)
    {
        try {
            $data = AppVersionService::getUpdateInfo($request->post('version_code', 100));
            return ok_rsp('成功', $data);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }


    public function siteInfo(Request $request)
    {
        try {
            $data = ConfigService::getByGroup('site');

            $data['site_logo'] = full_url($data['site_logo']);

            return ok_rsp('成功', $data);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function areas(Request $request)
    {
        $parentId = $request->post('parent_id', 0);

        try {
            $data = AreaService::getAreas($parentId);
            return ok_rsp('成功', $data);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function cities(Request $request)
    {
        try {
            $data = AreaService::cities();
            return ok_rsp('成功', $data);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function sendSms(Request $request)
    {
        try {
            $mobile = $request->post('mobile');
            $scene = $request->post('scene');
//            $token = $request->post('token');

            $user = User::where('id', get_user_id())->first();

            if (!$mobile) {
                $mobile = $user['mobile'];

                if (!$mobile) {
                    throw new \Exception('请输入手机号码');
                }
            }

//            if (CaptchaService::validateToken($mobile, $scene, $token) === false) {
//                return err_rsp('验证码错误或已过期');
//            }


            SmsService::send($mobile, $scene);
            return ok_rsp('成功');
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }

    }

    public function protocol(Request $request)
    {
        try {
            $key = $request->post('key');
            $language = $request->post('language', 'zh');
            $data = ArticleService::detail($key, $language);
            return ok_rsp('成功', $data);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function showProtocol(Request $request)
    {
        $data = ArticleService::detail($request->get('key'));
        return $data['content'];
    }

    public function kefu(Request $request)
    {
        try {
            $config = ConfigService::getByGroup('kefu');
            $config['kefu_qrcode'] = full_url($config['kefu_qrcode']);
            return ok_rsp('成功', $config);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function expressList(Request $request)
    {
        try {
            return ok_rsp('成功', ExpressCompany::all()->toArray());
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function languages(Request $request)
    {
        try {
            $languages = Base::LANGUAGE_TEXT;

            $data = [];

            foreach ($languages as $key=>$value) {
                $data[] = [
                    'key' => $key,
                    'value' => $value
                ];
            }


            return ok_rsp('成功', ['languages' => $data]);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function question(Request $request)
    {
        try {
            $page = $request->post('page', 1);
            $length = $request->post('page', 10);
            $categoryId = $request->post('category_id');

            $data = QuestionService::list($page, $length, $categoryId);
            return ok_rsp('成功', $data);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function priceConfig(Request $request)
    {
        try {
            $data = ConfigService::priceConfig();
            return ok_rsp('成功', $data);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function touristConfig(Request $request)
    {
        try {
            $data = ConfigService::touristConfig();
            return ok_rsp('成功', $data);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function withdrawConfig(Request $request)
    {
        try {
            $config = ConfigService::getByGroup('shop');

            return ok_rsp('成功', ['min_withdraw_amount' => $config['min_withdraw_amount'], 'withdraw_fee' => $config['withdraw_fee']]);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }

    }

    public function addSurnameConfig(Request $request)
    {
        try {

            return ok_rsp('成功', ConfigService::addSurnameConfig());
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }

    }

    public function getLiveBroadcastUrl(Request $request)
    {
        try {
            $data = ConfigService::get('logo');

            return ok_rsp('成功', ['url' => $data['live_broadcast_address']]);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function getCommonAddress(Request $request)
    {
        try {
            $data = ConfigService::get('logo');

            return ok_rsp('成功', ['address' => $data['common_address']]);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }
}